/**
 * 
 */
package com.manolo.server.dispatcher;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.manolo.server.event.ServerDataEvent;
import com.manolo.server.listener.ServerCommunicationListener;

/**
 * @author meyer
 * 
 */
public final class ServerCommunicationDispatcher {

	private static ServerCommunicationDispatcher instance;
	
	private List<ServerCommunicationListener> listeners;

	private ServerCommunicationDispatcher() {
		this.listeners = new ArrayList<ServerCommunicationListener>();
	}
	
	public void addServerCommunicationListener(ServerCommunicationListener listener){
		listeners.add(listener);
	}

	/**
	 * control singleton instance
	 * @return
	 */
	public static ServerCommunicationDispatcher getInstance(){
		if(instance == null){
			instance = new ServerCommunicationDispatcher();
		}
		return instance;
	}
	
	/**
	 * Dispatch event when client open connection
	 * @param event
	 */
	public void dispatchNewConnection(ServerDataEvent event){
		Iterator<ServerCommunicationListener> serverComIterator = listeners.iterator();
		while(serverComIterator.hasNext()){
			serverComIterator.next().onNewConnection(event);		
		}
	}
	/**
	 * Dispatch event on server receive message
	 * @param event
	 */
	public void dispatchReceiveMessage(ServerDataEvent event){
		Iterator<ServerCommunicationListener> serverComIterator = listeners.iterator();
		while(serverComIterator.hasNext()){
			serverComIterator.next().onReceiveMessage(event);		
		}
	}
	/**
	 * Dispatch event when socket client the close connection
	 * @param event
	 */
	public void dispatchCloseConnetion(ServerDataEvent event){
		Iterator<ServerCommunicationListener> serverComIterator = listeners.iterator();
		while(serverComIterator.hasNext()){
			serverComIterator.next().onCloseConnetion(event);		
		}
	}
	
	
}
